/*
 * @Author: 白酒煮饭
 * @Date: 2019-01-07 14:25:48
 * @LastEditors: QQ: 1641763174
 * @LastEditTime: 2020-10-19 21:28:03
 */
"ui";

const baseUrl = "http://abc.svip925.top/";
const versionCode = 6;
const versionName = "0.6.5";
const My_User = (device.sdkInt > 27) ? device.getAndroidId() : device.getIMEI(); //备份账号
const curFileName = "脚本云";
var TextDic = {
    qq: "是否添加QQ群反馈问题或者向作者提出你宝贵的建议",
    help: "1.脚本备份收费吗？\n答：不收费，脚本备份永久免费\n\n2.存储空间有限制吗？\n答：存储空间不限量不限速\n\n3.要不要注册？我的用户名是啥？\n答：不用注册，我们默认你的账号就手机的IMEI,当然，你也可以自定义你的账号，只有不是中文名就行\n\n4.我的账号会不会被盗？\n答：只有你不泄露你的账号，就不会被盗，账号非常重要，请妥善保管，建议使用之前自己修改下账号。\n\n5.上传的文件支不支持分享？\n答：目前是不支持分享的。\n\n6.支持脚本项目的备份吗？\n答：很遗憾，是不支持的，目前仅支持单脚本文件的上传\n\n7.json、txt、ini、xml这些文件能上传吗？\n答：目前仅支持js文件的上传，json、txt、ini、xml文件以后会支持\n\n8.下载的文件，存放在哪里？\n答：下载的文件都会存放到备份路径\n\n9.怎么设置备份路径？\n答：在第一页，底部第一个按钮，然后打开有js文件的文件夹，并选择其中一个js文件\n\n10.对上传的文件名有什么条件吗？\n答：有的，文件名不能带有+、&、/\n\n11.为什么有的文件会上传失败？\n答：可能是网络问题，或者是服务器抽风啦，重新试下就好了\n\n12.为什么网盘上的脚本不能删除？刷新之后还有？\n答：可能是你的文件名带有特殊字符",
    msg: "此脚本仅为Auto.Js的使用者，提供服务支持，我们开发的原因是我们很多时候，常常会因为忘记了备份脚本导致自己辛辛苦苦编写的脚本被垃圾清理误删除，或者手机不小心掉了等等，这是我们是不能忍受的，所以此工具的诞生意义就在于解决这些烦恼。无需注册，我们会根据你的手机IMEI创建一个文件夹，里面存放的你的脚本，或者你自己用的QQ也行，不过不能是中文。\n\n如果你有好的想法或者建议欢迎向我们反馈。\n\n感谢@笔青居提供的上传及获取列表的PHP源码"
};
var isVisibil = false, upLog = null;
var Local_List = [],
    Service_List = [],
    marketList = [],
    DataTemp = [];

var StartDirFile = new java.io.File("/sdcard/脚本");
var basePath = new java.io.File(StartDirFile);

ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title=" {{curFileName+' v'+versionName}}" >
                    <input id="search" hint="输入搜索内容" layout_weight="1" visibility="gone" />
                    <img src="@drawable/ic_search_black_48dp" id="scro" desc="搜索" layout_gravity="right" tint="#ffffff" bg="?selectableItemBackgroundBorderless" h="28" />
                </toolbar>
                <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
                <frame>
                    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout id="swipe1">
                        <vertical>
                            <text id="text" w="*" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="start" />
                            <progressbar id="progress" w="*" h="auto" indeterminate="true" layout_gravity="top" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal" />
                            <list id="list" layout_weight="1">
                                <card w="*" margin="5" cardCornerRadius="10dp" cardElevation="1dp" >
                                    <horizontal gravity="center_vertical" bg="{{getBG(file.path)}}">
                                        <vertical layout_weight="1" padding="5">
                                            <text w="*" textSize="20sp" textColor="#000000" maxLines="1" ellipsize="middle" text="{{this.name}}" />
                                            {/* <text w="*" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="start" text="{{file.path}}" /> */}
                                            <text w="*" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="middle" text="{{getSize(file.length())}}" />
                                        </vertical>
                                        <checkbox id="done" h="*" margin="4" visibility="{{isCanLook}}" />
                                    </horizontal>
                                </card>
                            </list>
                            <horizontal gravity="center">
                                <button id="dxup" layout_weight="1" text="多选" />
                                <button id="openup" layout_weight="1" text="开始上传" />
                                <button id="back" layout_weight="2" text="返回" />
                                <button id="exit" text="退出" layout_weight="1" />
                            </horizontal>
                        </vertical>
                    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
                </frame>
                <frame>
                    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout id="swipe2">
                        <vertical>
                            <text id="text2" w="*" text="服务器文件列表加载中..." gravity="left" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="start" />
                            <progressbar id="progress2" w="*" h="auto" indeterminate="true" layout_gravity="top" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal" />
                            <list id="list2" layout_weight="1">
                                <card w="*" margin="5" cardCornerRadius="10dp" cardElevation="1dp" >
                                    <horizontal gravity="center_vertical" bg="#d3d3d3">
                                        <vertical layout_weight="1" padding="5">
                                            <text w="*" textSize="20sp" textColor="#000000" maxLines="1" ellipsize="middle" text="{{this.fileName}}" />
                                            <text w="*" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="start" text="上传时间：{{TimeToDate(updataTime)}}" />
                                        </vertical>
                                        <checkbox id="done" h="*" margin="4" checked="{{done}}" visibility="{{isCanLook}}" />
                                    </horizontal>
                                </card>
                            </list>
                            <horizontal gravity="center">
                                <button id="duxuan" layout_weight="1" text="多选" />
                                <button id="allDown" layout_weight="1" text="开始下载" />
                                <button id="del" layout_weight="1" text="删除" />
                            </horizontal>
                        </vertical>
                    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
                </frame>
                <frame>
                    <vertical>
                        <vertical>
                            <progressbar id="progress3" w="*" h="auto" indeterminate="true" layout_gravity="top" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal" />
                            <text padding="5" text="共享脚本是用户自愿上传的，大家都可以上传下载，如果你发现好的脚本欢迎上传分享，我们一起共同进步。" />
                            <list id="list3" layout_weight="1">
                                <card w="*" margin="5" cardCornerRadius="10dp" cardElevation="1dp" >
                                    <horizontal gravity="center_vertical" bg="#d3d3d3">
                                        <vertical layout_weight="1" padding="5">
                                            <text w="*" textSize="20sp" textColor="#000000" maxLines="1" ellipsize="middle" text="{{this.fileName}}" />
                                            <text w="*" textSize="16sp" textColor="#000000" maxLines="1" ellipsize="start" text="上传时间：{{TimeToDate(updataTime)}}" />
                                        </vertical>
                                        <checkbox id="done" h="*" margin="4" checked="{{done}}" visibility="{{isCanLook}}" />
                                    </horizontal>
                                </card>
                            </list>
                        </vertical>
                    </vertical>
                </frame>
            </viewpager>
        </vertical>
    </drawer>
);
activity.setSupportActionBar(ui.toolbar);
ui.viewpager.setTitles(["本机脚本", "云端脚本", "共享脚本"]);
ui.tabs.setupWithViewPager(ui.viewpager);
/**
 * Log重写
 */
log = function () {
    var arg = new Array;
    for (var i = 0; i < arguments.length; i++) {
        arg.push(arguments[i]);
    };
    ui.run(() => {
        ui.text.setText(new Date().toTimeString().split(" ")[0] + "/: " + String(arg));
        ui.text2.setText(new Date().toTimeString().split(" ")[0] + "/: " + String(arg));
    });
};
var Threads = threads.start(function () {
    setInterval(() => { }, 1000);
});
ui.exit.click(ui.finish);
ui.text.click(toBack);
ui.back.click(toBack);
ui.scro.click(function (v) {
    if (!isVisibil) {
        isVisibil = true;
        ui.search.visibility = 0;
    } else {
        isVisibil = false;
        ui.search.visibility = 8;
    }
})
ui.dxup.click(function (v) {
    if (v.getText() == "多选") {
        v.setText("取消");
        Local_List.forEach(item => {
            if (files.isFile(item.file)) {
                item.isCanLook = "visible";
            }
        });
        ui.list.adapter.notifyDataSetChanged();
    } else {
        v.setText("多选");
        DataTemp = [];
        Local_List.forEach(item => {
            item.isCanLook = "gone";
        });
        ui.list.adapter.notifyDataSetChanged();
    };
});
ui.emitter.on("back_pressed", e => {
    e.consumed = toBack();
});
ui.list.on("item_bind", function (itemView, itemHolder) {
    itemView.done.on("check", function (checked) {
        let item = itemHolder.item;
        item.done = checked;
        if (checked) {
            DataTemp.push({
                "fileName": item.name,
                "filePath": item.file
            })
        } else {
            remove(DataTemp, item.name);
        }
    });
});
ui.list.on("item_click", function (item) {
    var file = item.file;
    var name = item.name;
    if (file.isDirectory()) {
        basePath = file;
        加载本地脚本(basePath);
    } else if (file.isFile()) {
        let a = ["打开", "运行", "上传到我的云脚本库", "共享此脚本", "重命名", "删除", "取消"];
        dialogs.select(name, a, function (i) {
            switch (i) {
                case 0:
                    OpenFile(file);
                    break;
                case 1:
                    confirm("提示", "请确保你要运行的脚本经过测试且成功运行，否则可能会导致软件崩溃，是否继续？", (value) => {
                        if (value) { RunScript(files.read(file)); }
                    })
                    break;
                case 2:
                    Threads.setTimeout(() => {
                        上传脚本(My_User, "", file, name);
                    }, 0)
                    break;
                case 3:
                    Threads.setTimeout(() => {
                        上传脚本("Shared_account", "", file, name);
                    }, 0)
                    break;
                case 4:
                    rawInput("请输入新名称", name).then(newName => {
                        if (newName == null) {
                            toast("重命名失败"); return;
                        } else if (newName.match(/^\s*$/)) {
                            toast("文件不能为空"); return;
                        } else if (newName !== null) {
                            if (files.rename(file, newName)) {
                                toastLog("重命名成功!!!");
                            }
                        }
                    });
                    break;
                case 5:
                    if (files.remove(file)) toast("文件删除成功!");
                    加载本地脚本(basePath);
                    break;
            }
        });
    };

});
ui.list2.on("item_bind", function (itemView, itemHolder) {
    itemView.done.on("check", function (checked) {
        let item = itemHolder.item;
        item.done = checked;
        if (checked) {
            DataTemp.push({
                "fileName": item.fileName
            });
        } else {
            remove(DataTemp, item.fileName);
        }
    });
});
ui.list2.on("item_click", function (items, pos) {
    threads.start(function () {
        let item = items.fileName;
        let a = ["下载", "运行", "删除", "查看", "取消"];
        dialogs.select(item, a, function (i) {
            switch (i) {
                case 0:
                    Threads.setTimeout(() => {
                        下载脚本(My_User, "", basePath, item);
                    }, 0)
                    break;
                case 1:
                    confirm("提示", "请确保你要运行的脚本经过测试且成功运行，否则可能会导致软件崩溃，是否继续？", (value) => {
                        if (value) {
                            Threads.setTimeout(() => {
                                toast("正在从服务器获取脚本，请稍候。。。");
                                let code = 下载脚本(My_User, "", basePath, item);
                                try {
                                    engines.execScript("temp", code);
                                } catch (e) {
                                    toast("代码运行出错");
                                }
                            }, 0)
                        };
                    });
                    break;
                case 2:
                    列表删除(true, pos, item);
                    break;
                case 3:
                    Threads.setTimeout(() => {
                        toast("正在打开，请稍候。");
                        files.write("/sdcard/.temp.js", http.get(baseUrl + "download.php?user=" + My_User + "&name=" + item).body.string());
                        OpenFile("/sdcard/.temp.js");
                    }, 0)
                    break;
            }
        });
    });
});
ui.list3.on("item_click", function (items) {
    let item = items.fileName;
    let a = ["下载", "查看", "取消"];
    dialogs.select(item, a, function (i) {
        switch (i) {
            case 0:
                Threads.setTimeout(() => {
                    下载脚本("Shared_account", "", basePath, item);
                }, 0)
                break;
            case 1:
                Threads.setTimeout(() => {
                    toast("正在打开，请稍候。");
                    files.write("/sdcard/.temp.js", http.get(baseUrl + "download.php?user=Shared_account&name=" + item).body.string());
                    OpenFile("/sdcard/.temp.js");
                }, 0)
                break;
        }
    });
})
ui.openup.click(function (v) {
    if (ui.dxup.getText() == "取消") {
        Threads.setTimeout(() => {
            if (多选操作("UP", DataTemp)) {
                ui.run(function () {
                    ui.openup.setText("开始上传");
                });
            }
        }, 0)
    } else if (v.getText() == "开始上传" && ui.dxup.getText() != "取消") {
        confirm("提示", "该操作会全部上传列表的文件，是否继续？", (value) => {
            if (value) {
                ui.run(function () {
                    v.setText("停止上传");
                    ui.text.text("上传开始");
                });
                Threads.setTimeout(() => {
                    if (多选操作("UP", Local_List)) {
                        ui.run(function () {
                            ui.openup.setText("开始上传");
                        });
                    }
                }, 0)
            }
        });
    } else if (v.getText() == "停止上传") {
        toast("已停止");
        ui.run(function () {
            ui.text.setText("上传已停止");
            v.setText("开始上传");
        });
        isRun = false;
    }
});
ui.swipe1.setOnRefreshListener({
    onRefresh: function () {
        ui.run(function () {
            ui.text.setText("本地文件列表刷新中...");
            ui.progress.setVisibility(0);
        });
        // 加载云端脚本(My_User);
        加载本地脚本(basePath)
        ui.swipe1.setRefreshing(false);
    },
});
ui.swipe2.setOnRefreshListener({
    onRefresh: function () {
        ui.run(function () {
            ui.text2.setText("服务器文件列表加载中...");
            ui.progress2.setVisibility(0);
        });
        加载云端脚本(My_User);
        ui.swipe2.setRefreshing(false);
    },
});
ui.allDown.click(function (v) {
    if (ui.duxuan.getText() == "取消") {
        Threads.setTimeout(() => {
            if (多选操作("DOWN", DataTemp)) {
                ui.run(function () {
                    ui.allDown.setText("开始下载");
                });
            }
        }, 0)
    } else if (v.getText() == "开始下载" && ui.duxuan.getText() != "取消") {
        confirm("提示", "该操作会全部下载列表的文件，是否继续？", (value) => {
            if (value) {
                ui.run(function () {
                    v.setText("停止下载");
                    ui.text2.text("下载开始");
                });
                Threads.setTimeout(() => {
                    if (多选操作("DOWN", Service_List)) {
                        ui.run(function () {
                            ui.duxuan.setText("开始下载");
                        });
                    }
                }, 0)
            }
        });
    } else if (v.getText() == "停止下载") {
        toast("已停止");
        ui.run(function () {
            ui.text2.setText("下载已停止");
            v.setText("开始下载");
        });
        isRun = false;
    }
});
ui.duxuan.click(function (v) {
    if (v.getText() == "多选") {
        v.setText("取消");
        Service_List.forEach(item => {
            item.isCanLook = "visible";
        });
        ui.list2.adapter.notifyDataSetChanged();
    } else {
        v.setText("多选");
        DataTemp = [];
        Service_List.forEach(item => {
            item.isCanLook = "gone";
        });
        ui.run(function () {
            ui.list2.adapter.notifyDataSetChanged();
        });
    };
});
ui.del.click(function (v) {
    if (v.getText() == "删除" && ui.duxuan.getText() == "取消") {
        confirm("提示", "该操作会删除已选择的文件，删除后无法恢复，是否继续？", (value) => {
            if (value) {
                ui.run(function () {
                    v.setText("停止删除");
                    ui.del.text("删除");
                });
                Threads.setTimeout(() => {
                    if (多选操作("DEL", DataTemp)) {
                        ui.run(function () {
                            ui.del.setText("删除");
                        });
                    }
                }, 0)
            }
        });
    } else {
        toast("请先选择文件");
        return;
    }
});
ui.emitter.on("create_options_menu", menu => {
    menu.add("更新日志");
    menu.add("反馈");
    menu.add("帮助");
    menu.add("关于");
});
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "帮助":
            alert("帮助", TextDic.help);
            break;
        case "更新日志":
            alert("更新日志", upLog.content);
            break;
        case "反馈":
            confirm("提示", TextDic.qq, (e) => {
                if (e) {
                    app.startActivity({
                        action: "android.intent.action.VIEW",
                        data: "mqqapi://card/show_pslcard?card_type=group&uin=952614347",
                        packageName: "com.tencent.mobileqq",
                    });
                }
            });
            break;
        case "关于":
            alert("关于 " + versionName, TextDic.msg);
            break;
    }
    e.consumed = true;
});
ui.search.addTextChangedListener(new android.text.TextWatcher({
    afterTextChanged: function (key) {
        var itemId = ui.viewpager.getCurrentItem();
        if (key != "") {
            if (itemId == 0) {
                ui.list.setDataSource(search(ui.list.getDataSource(), function (item) {
                    return item.name.toUpperCase().indexOf((key + "").toUpperCase()) != -1;
                }));
            } else if (itemId == 1) {
                ui.list2.setDataSource(search(ui.list2.getDataSource(), function (item) {
                    return item.fileName.toUpperCase().indexOf((key + "").toUpperCase()) != -1;
                }));
            } else if (itemId == 2) {
                ui.list3.setDataSource(search(ui.list3.getDataSource(), function (item) {
                    return item.fileName.toUpperCase().indexOf((key + "").toUpperCase()) != -1;
                }));
            }
        } else {
            if (itemId == 0) {
                ui.list.setDataSource(Local_List);
            } else if (itemId == 1) {
                ui.list2.setDataSource(Service_List);
            } else if (itemId == 2) {
                ui.list3.setDataSource(marketList);
            }
        }
    }
}));
main()
function main() {
    加载本地脚本(basePath);
    加载云端脚本(My_User);
    共享脚本("Shared_account");
    checkVersion();
}
function 共享脚本(User) {
    threads.start(function () {
        let res = http.get(baseUrl + "codelist.php?user=" + User);
        if (res.statusCode != 200) {
            toast("请求失败: " + res.statusCode + " " + res.statusMessage);
            return;
        }
        let json = res.body.json();
        let UpDate = json.map(function (file) {
            return {
                type: file.type,
                fileName: file.fileName,
                filePath: file.filePath,
                updataTime: file.updataTime,
                done: false,
                isCanLook: "gone"
            };
        });
        marketList = UpDate;
        ui.run(function () {
            ui.list3.setDataSource(marketList);
            ui.progress3.setVisibility(8);
        });
        string(2, "共享脚本" + marketList.length);
    })
}
function 加载本地脚本(path) {
    var file = new java.io.File(path);
    var fileList = file.listFiles();
    var dirList = fileList.filter(function (file) {
        return file.isDirectory();
    }).sort();
    var fileList = fileList.filter(function (file) {
        return file.isFile();
    }).sort();
    ui.text.setText(String(path));
    var UpDate = dirList.concat(fileList).map(function (file) {
        return {
            name: file.name,
            file: file,
            isFile: (files.isDir(file)) ? true : false,
            isCanLook: "gone"
        };
    }); Local_List = UpDate;
    ui.run(function () {
        ui.list.setDataSource(Local_List);
        ui.dxup.setText("多选");
        ui.progress.setVisibility(8);
    });
    var jsnums = files.listDir(basePath, function (name) {
        return name.endsWith(".js") && files.isFile(files.join(basePath, name));
    });
    string(0, "本地脚本" + jsnums.length);

};
function 加载云端脚本(User, is) {
    threads.start(function () {
        let res = http.get(baseUrl + "codelist.php?user=" + User);
        if (res.statusCode != 200) {
            toast("请求失败: " + res.statusCode + " " + res.statusMessage);
            return;
        }
        let json = res.body.json();
        let UpDate = json.map(function (file) {
            return {
                type: file.type,
                fileName: file.fileName,
                filePath: file.filePath,
                updataTime: file.updataTime,
                done: false,
                isCanLook: "gone"
            };
        });
        ui.run(function () {
            ui.list2.setDataSource(UpDate);
            ui.progress2.setVisibility(8);
            let txt = "服务器文件列表加载完成✅";
            ui.text2.text(txt);
            ui.duxuan.setText("多选");
        });
        Service_List = UpDate;
        string(1, "云端脚本" + Service_List.length);
    })
}
/**
 * 设置标签的文字
 * @param {*} id  标签ID
 * @param {*} text  文字
 */
function string(id, text) {
    ui.run(function () {
        ui.tabs.getTabAt(id).setText(text);
    });
}

function remove(Arr, val) {
    for (let i in Arr) {
        if (Arr[i].fileName == val) {
            Arr.splice(i, 1);
        }
    }
};
function 列表删除(id, pos, Name) {
    if (id) {
        删除文件(Name);
        if (pos) {
            Service_List.splice(pos, 1);
            string(1, String("云端脚本" + Service_List.length));
        }
    } else {
        if (files.remove(Name)) toast("文件删除成功!");
        Local_List.splice(pos, 1);
        string(0, String("本机脚本" + Local_List.length));
    }
}
/**
 * 读取代码并运行脚本
 * @param {*} code  脚本代码
 */
function RunScript(code) {
    Threads.setTimeout(() => {
        try {
            engines.execScript("temp", code);
        } catch (e) {
            toast("代码运行出错");
        }
    }, 0)
}
function 下载脚本(User, txt, localPath, name) {
    try {
        let res = http.get(baseUrl + "download.php?user=" + User + "&name=" + name);
        if (res.statusCode != 200) {
            toastLog("下载失败: " + res.statusCode + " " + res.statusMessage);
            return;
        }
        let str = res.body.string();
        ui.run(function () {
            ui.text2.text(txt + name + " ：下载完成");
        });
        if (localPath) {
            files.write(localPath + "/" + name, str);
        } else {
            return str;
        }
    } catch (e) {
        console.log(e)
        toastLog("下载出错啦");
        return false;
    }
}
/**
 * 打开js脚本
 * @param {*} file  文件路径
 */
function OpenFile(file) {
    var Extension = files.getExtension(file);
    if (Extension == "js" || Extension == "txt" || Extension == "json") {
        if (context.getPackageName() == "org.autojs.autojs") {
            app.startActivity({
                data: "file:" + file,
                packageName: "org.autojs.autojs",
                className: "org.autojs.autojs.ui.edit.EditActivity_",
            });
        } else if (context.getPackageName() == "org.autojs.autojspro") {
            app.startActivity({
                data: "file:" + file,
                packageName: "org.autojs.autojspro",
                className: "org.autojs.autojs.external.open.OpenActivity",
            });
        }
    } else {
        app.viewFile(file);
    }
}
function 上传脚本(User, txt, path, name) {
    try {
        let res = http.postMultipart(baseUrl + "pushcode.php?user=" + User, {
            "file": open(path)
        });
        let json = res.body.json();
        let body = json["code"];
        if (body == 200 || body == 201 || body == 202) {
            ui.run(function () {
                ui.text.text(txt + name + "：" + json["msg"]);
            });
        } else {
            toastLog("上传出错啦!!");
        }
    } catch (e) {
        console.log(e), toastLog("脚本上传出错 ");
    }
}
function 多选操作(isUp, list) {
    let count = 0;
    for (let i in list) {
        if (isUp == "UP") {
            上传脚本(My_User, String(parseInt(i) + 1 + "/" + list.length) + "   ", list[i].filePath, list[i].fileName);
        } else if (isUp == "DEL") {
            列表删除(true, false, list[i].fileName);
        } else if (isUp == "DOWN") {
            下载脚本(My_User, String(parseInt(i) + 1 + "/" + list.length) + "   ", basePath, list[i].fileName);
        }
        count++;
    }
    DataTemp = [];
    加载云端脚本(My_User);
    加载本地脚本(basePath);
    ui.run(function () {
        if (isUp == "UP") {
            ui.text.setText(count + "个文件上传完成");
        } else if (isUp == "DOWN") {
            ui.text2.setText(count + "个文件下载完成");
        }
    });
    return true;
}
function 删除文件(filename) {
    var res = http.get(baseUrl + "del.php?user=" + My_User + "&name=" + filename);
    let json = res.body.json();
    try {
        let body = json["code"];
        if (body == 200 || body == 201 || body == 202) {
            ui.run(function () {
                ui.text2.text(filename + "：" + json["msg"]);
            });
        } else {
            toastLog("删除出错啦!!");
        }
    } catch (e) {
        log(e);
        toastLog("删除出错");
    }
}
/**
 * 版本检测更新
 */
function checkVersion() {
    threads.start(function () {
        let res = http.get(baseUrl + "updata.json");
        upLog = http.get(baseUrl + "/yun_code/upLog.json").body.json();
        if (res.statusCode != 200) {
            toast("更新失败: " + res.statusCode + " " + res.statusMessage);
            return;
        }
        let json = res.body.json();
        if (versionCode < json["versionCode"]) {
            confirm(json["title"] + json["versionName"], json["content"], (value) => {
                if (value) {
                    threads.start(function () {
                        toast("正在更新。。请稍候。。。。");
                        Path = engines.myEngine().cwd();
                        codePath = Path + "/脚本云 v" + versionName + ".js";
                        files.write(codePath, http.get(json["url"]).body.string())
                        toast("正在打开。。。");
                        ui.finish();
                        engines.execScriptFile(codePath);
                    });
                }
            });
        }
    });
}
/**
 * 返回
 */
function toBack() {
    if (!basePath.equals(StartDirFile)) {
        basePath = basePath.getParentFile();
        加载本地脚本(basePath);
        return true;
    } else {
        return false;
    };
};
/**
 * 获取文件类型特定的颜色
 * @param {String} file 
 */
function getBG(file) {
    var fileType = {
        文本: {
            color: ['#ff007fff', '#ffffa500', '#ffffff00', '#ff8b00ff', '#ff8b0ff0'],
            ends: ["js", "txt", "json", "xml", "ini"]
        },
        图片: {
            color: ['#ff00ff00', '#ffff0000'],
            ends: ["png", "jpg"]
        },
        安装包: {
            color: ['#ff0000ff'],
            ends: ["apk"]
        }
    };
    var Extension = String(file).split(".").pop();
    for (var i in fileType) {
        for (var a = 0; a < fileType[i].ends.length; a++) {
            if (Extension == fileType[i].ends[a]) {
                var b = fileType[i].color[a]
            };
        }
    };
    return file.directory ? AA("#3f0a141e") : AA(b);
    function AA(c) {
        var r = colors.red(c);
        var g = colors.green(c);
        var b = colors.blue(c);
        return colors.toString(colors.argb(63, r, g, b));
    };
};
/**
 * 格式化文件大小
 * @param {*} size 
 */
function getSize(size) {
    var asize;
    switch (true) {
        case 1 <= Math.round(size / 1073741824):
            asize = Math.floor(size / 1073741824 * 100) / 100 + "MB";
            break;
        case 1 <= Math.round(size / 1048576):
            asize = Math.floor(size / 1048576 * 100) / 100 + "MB";
            break;
        case 1 <= Math.round(size / 1024):
            asize = Math.floor(size / 1024 * 100) / 100 + "KB";
            break;
        default:
            asize = size + "B";
    };
    return asize;
};
/**
 * 时间格式转换
 * @param {*} time 
 */
function TimeToDate(time) {
    return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(parseInt(time + "000")));
}
/**
 * 从一个列表中搜索文件
 * @param {*} list  列表
 * @param {*} filter 要搜索的文件名
 */
function search(list, filter) {
    var sum = threads.disposable();
    threads.start(function () {
        var filterList = list.filter(function (item) {
            return filter(item);
        });
        sum.setAndNotify(filterList);
    });
    return sum.blockedGet();
}

